package datastructure.day02;

/**
 * @author: Gan
 * @date 2021/4/29 0029 19:29
 * @description: 用单链表实现栈
 **/
public class StackLinked {
    Node top;

    //压栈
    public void push(String value) {
        //先把传入的值装到一个新节点中
        Node node = new Node(value);
        //若栈空
        if (top == null) {
            top = node;
        } else {
            //栈不为空,压栈
            node.next = top;
            //更新top结点
            top = node;
        }
    }

    //出栈
    public String pop() {
        String value;
        if (isEmpty())
            throw new RuntimeException("Stack is empty!");
        //先保存栈顶元素
        value = top.value;
        top = top.next;
        return value;
    }

    //查看栈顶元素
    public String peek() {
        if (isEmpty())
            throw new RuntimeException("Illegal,Stack is empty!");
        return top.value;
    }

    //求栈的深度
    public int getStackDepth() {
        if (isEmpty())
            return 0;
        int depth = 0;
        //遍历指针
        Node pStr = top;
        while (pStr != null) {
            pStr = pStr.next;
            depth++;
        }
        return depth;
    }

    //判空
    public boolean isEmpty() {
        return top == null;
    }

    class Node {

        String value;
        Node next;

        public Node(String value) {
            this.value = value;
        }
    }
}
